package com.tyf.configuration;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GlobalFilter implements GatewayFilter, Ordered {


    private void logRequest(ServerHttpRequest request) {
        // 在此处记录请求相关信息，例如方法、路径、头信息、请求体等
        System.out.println("Request: " + request.getMethod() + " " + request.getURI());
    }

    private void logResponse(ServerHttpResponse response, Throwable throwable) {
        // 在此处记录响应相关信息，例如状态码、响应体、错误信息等
        String status = response.getStatusCode().toString();
        if (throwable != null) {
            status += ", Error: " + throwable.getMessage();
        }
        System.out.println("Response: " + status);
    }

    @Override
    public int getOrder() {
        // 设置过滤器执行顺序，可以根据需要调整
        return -1; // 保证这个过滤器在其他过滤器之前执行
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logRequest(exchange.getRequest());
        return chain.filter(exchange)
                .doOnError(throwable -> logResponse(exchange.getResponse(), throwable));
    }
}
